import aioredis
import json
from typing import AsyncGenerator

REDIS_URL = "redis://localhost:6379/0"  # Modify as needed
ANOMALY_DATA_PREFIX = "anomaly_data:"

async def fetch_and_delete_anomaly_data(redis_url: str = REDIS_URL) -> AsyncGenerator[dict, None]:
    """
    Asynchronously fetch all anomaly_data JSONs from Redis, yield each for analysis, and delete after fetching.
    Args:
        redis_url (str): Redis connection URL.
    Yields:
        dict: The anomaly_data JSON object.
    """
    redis = await aioredis.from_url(redis_url, decode_responses=True)
    try:
        # Find all keys with the anomaly_data prefix
        keys = await redis.keys(f"{ANOMALY_DATA_PREFIX}*")
        for key in keys:
            data = await redis.get(key)
            if data:
                try:
                    json_data = json.loads(data)
                    yield json_data
                except Exception as e:
                    # Optionally log or handle JSON decode errors
                    pass
            # Delete the key after fetching to avoid reprocessing
            await redis.delete(key)
    finally:
        await redis.close()
